package xyz.jcat.sco.admin.oauth2.server.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import xyz.jcat.common.web.Resp;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.web.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    private CreateTokenService createTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        try {
            OAuth2AccessToken token = createTokenService.createToken(request, authentication);
            WebUtils.writeJson(response, Resp.ok(token));
        }catch (Exception e) {
            log.error("create token error", e);
            WebUtils.writeJson(response, Resp.fail(RespCodeMsg.LOGIN_ERROR, e.getMessage()));
        }
    }

}
